package edu.ccut.saturn.component.impl.sql;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import edu.ccut.saturn.component.SaturnComponentException;

public class SqlTextInfo extends AbstractSqlTextItemInfo {

	private List<ParameterToken> tokens;

	private boolean hasToken = false;

	public String getSubSql(Map<String, Object> param) throws Exception {

		if (this.text != null) {

			if (isHasToken()) {
				StringBuffer textBuffer = new StringBuffer(text);

				for (ParameterToken token : tokens) {
					Object paramValue = param.get(token.getParamName());

					if (paramValue == null) {
						throw new SaturnComponentException("");
					}
//					token.setStartIndex(textBuffer.indexOf("${"));
//					token.setEndIndex(textBuffer.indexOf("}"));
					token.replace(textBuffer, (String) paramValue);
				}
				return textBuffer.toString();

			} else {
				return text;
			}
		}
		throw new SaturnComponentException("");
	}

	public SqlTextInfo(String sqlText) {
		super();
		this.text = sqlText;
		this.tokens = new ArrayList<ParameterToken>();
		initTokens();
	}

	private void initTokens() {
		int start = 0;
		int begin = 0;
		this.hasToken = false;

		if (this.text != null && !"".equals(text)) {

			while (start != -1 && begin != -1) {
				begin = text.indexOf(ParameterToken.TOKEN_START, start);

				if (begin != -1) {
					start = text.indexOf(ParameterToken.TOKEN_END, begin);

					if (start != -1) {
						ParameterToken token = new ParameterToken(begin, start,
								text.substring(begin + 2, start).trim());

						tokens.add(token);
					}
				}
			}

			if (tokens.size() > 0) {
				this.hasToken = true;
			}
		}
	}

	public boolean isHasToken() {
		return hasToken;
	}

	public List<ParameterToken> getTokens() {
		return tokens;
	}

}
